#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
环境检测和设置脚本 - 帮助安装依赖并检查环境配置
"""

import os
import sys
import subprocess
import importlib
import pkg_resources

def check_package_version(package_name):
    """检查包的版本"""
    try:
        package = pkg_resources.get_distribution(package_name)
        print(f"已安装 {package.project_name} 版本 {package.version}")
        return package.version
    except pkg_resources.DistributionNotFound:
        print(f"未安装 {package_name}")
        return None

def install_package(package):
    """安装指定的包"""
    print(f"正在安装 {package}...")
    try:
        subprocess.check_call([sys.executable, "-m", "pip", "install", package])
        print(f"{package} 安装成功！")
        return True
    except subprocess.CalledProcessError as e:
        print(f"安装 {package} 失败: {e}")
        return False

def check_browser():
    """检查浏览器环境"""
    print("\n正在检测浏览器环境...")
    try:
        from DrissionPage import ChromiumOptions
        co = ChromiumOptions()
        
        # 尝试获取浏览器路径
        try:
            browser_path = co.binary_location
            if browser_path and os.path.exists(browser_path):
                print(f"已找到浏览器路径: {browser_path}")
                return True
            else:
                print(f"浏览器路径可能无效: {browser_path}")
                return False
        except Exception as e:
            print(f"获取浏览器路径失败: {e}")
            return False
    except ImportError:
        print("未安装DrissionPage，请先安装依赖")
        return False
    except Exception as e:
        print(f"检测浏览器时出错: {e}")
        return False

def main():
    """主函数 - 检测和设置环境"""
    print("=== 小红书爬虫环境检测和设置工具 ===\n")
    
    # 检查Python版本
    print(f"Python版本: {sys.version}")
    
    # 检查关键依赖
    drission_version = check_package_version("DrissionPage")
    requests_version = check_package_version("requests")
    gradio_version = check_package_version("gradio")
    
    # 如果DrissionPage未安装或版本不正确，尝试安装
    if drission_version != "4.0.0b3":
        print("\n需要安装DrissionPage 4.0.0b3版本...")
        install_package("DrissionPage==4.0.0b3")
        drission_version = check_package_version("DrissionPage")
    
    # 检查浏览器环境
    browser_ok = check_browser()
    
    # 显示检测结果
    print("\n=== 环境检测结果 ===")
    print(f"Python版本: {sys.version}")
    print(f"DrissionPage版本: {drission_version}")
    print(f"Requests版本: {requests_version}")
    print(f"Gradio版本: {gradio_version}")
    print(f"浏览器环境: {'正常' if browser_ok else '异常'}")
    
    if drission_version != "4.0.0b3" or not browser_ok:
        print("\n⚠️ 环境存在问题，可能影响爬虫运行")
        print("建议执行以下操作:")
        
        if drission_version != "4.0.0b3":
            print("1. 运行: pip install DrissionPage==4.0.0b3")
            
        if not browser_ok:
            print("2. 确保已安装最新版Chrome或Edge浏览器")
            print("3. 如果浏览器已安装但未检测到，可以尝试手动设置浏览器路径")
    else:
        print("\n✅ 环境检测通过，可以正常运行爬虫")
    
    print("\n提示: 如果遇到问题，可以尝试重新安装依赖:")
    print("pip install -r requirements.txt")

if __name__ == "__main__":
    main() 